<!--文件上传组件-->
<template>
	<div class="upload-file">
		<!---拖拽上传-->
		<el-upload
			ref="fileUpload"
			v-if="props.type === 'default'"
			:action="baseURL + other.adaptationUrl(props.uploadFileUrl)"
			:name="props.file"
			:before-upload="handleBeforeUpload"
			:file-list="fileList"
			:show-file-list="props.showFileList"
			:headers="headers"
			:limit="limit"
			:on-error="handleUploadError"
			:on-remove="handleRemove"
			:on-preview="handlePreview"
			:on-change="handleChange"
			:data="formData"
			:auto-upload="autoUpload"
			:on-success="handleUploadSuccess"
			:on-progress="handleProgress"
			:on-exceed="handleExceed"
			:http-request="handleHttpUpload"
			class="upload-file-uploader"
			drag
			multiple
		>
			<template #trigger>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">
					{{ $t('excel.operationNotice') }}
					<em>{{ $t('excel.clickUpload') }}</em>
				</div>
			</template>
			<template #tip>
				<div class="el-upload__tip" v-if="props.isShowTip">
					{{ $t('excel.pleaseUpload') }}
					<template v-if="props.fileSize">
						{{ $t('excel.size') }} <b style="color: #f56c6c">{{ props.fileSize }}MB</b></template
					>
					<template v-if="props.fileType">
						{{ $t('excel.format') }} <b style="color: #f56c6c">{{ props.fileType.join('/') }}</b>
					</template>
					{{ $t('excel.file') }}
				</div>
			</template>
			<!---非自动上传-->
			<el-button v-if="props.autoUpload===false" type="success" @click="submitUpload"  :icon="UploadFilled"  size="large"
				class="p-2 mt-4">
				{{ $t('excel.clickServer') }}
			</el-button>
		</el-upload>
		
		<!---简单上传-->
		<el-upload
			ref="fileUpload"
			v-if="props.type === 'simple'"
			:action="baseURL + other.adaptationUrl(props.uploadFileUrl)"
			:name="props.file"
			:before-upload="handleBeforeUpload"
			:file-list="fileList"
			:show-file-list="props.showFileList"
			:headers="headers"
			:limit="limit"
			:auto-upload="autoUpload"
			:on-error="handleUploadError"
			:on-remove="handleRemove"
			:data="formData"
			:on-change="handleChange"
			:on-success="handleUploadSuccess"
			:on-progress="handleProgress"
			:on-exceed="handleExceed"
			:http-request="handleHttpUpload"
			class="upload-file-uploader"
			multiple
		>
			<template #trigger>
				<el-button type="primary" :icon="Plus" size="large" plain class="mr-4">
					{{ t('excel.clickUpload') }}
				</el-button>
			</template>
			<!---非自动上传-->
			<el-button v-if="props.autoUpload===false" type="success" @click="submitUpload" :icon="UploadFilled"  size="large"  plain>
				{{ t('excel.clickServer') }}
			</el-button>
		</el-upload>
	</div>
</template>

<script setup lang="ts" name="upload-file">
import { Plus, UploadFilled } from '@element-plus/icons-vue';
import CryptoJS from 'crypto-js';
import type { UploadRequestOptions } from 'element-plus';
import { formContextKey, formItemContextKey, UploadFile, UploadFiles, UploadProgressEvent, UploadUserFile } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import other from '/@/utils/other';
import request from '/@/utils/request';
import { Session } from '/@/utils/storage';

const props = defineProps({
	modelValue: [String, Array],
	// 数量限制
	limit: {
		type: Number,
		default: 5,
	},
	// 大小限制(MB)
	fileSize: {
		type: Number,
		default: 5,
	},
	showFileList:{
		type:Boolean,
		default:true,
	},
	fileType: {
		type: Array,
		default: () => ['png', 'jpg', 'jpeg', 'doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'pptx'],
	},
	// 是否显示提示
	isShowTip: {
		type: Boolean,
		default: true,
	},
	file: {
		type: String,
		default: 'file',
	},
	uploadFileUrl: {
		type: String,
		default: '/admin/file/upload',
	},
	type: {
		type: String,
		default: 'simple',
		validator: (value: string) => {
			return ['default', 'simple'].includes(value);
		},
	},
	data: {
		type: Object,
		default: {},
	},
	dir: {
		type: String,
		default: '',
	},
	autoUpload: {
		type: Boolean,
		default: false,//减少自动上传的压力
	},
});

const emit = defineEmits(['update:modelValue', 'change']);

const number = ref(0);
const fileList = ref([]) as any;
const uploadList = ref([]) as any;
const fileUpload = ref();
const { t } = useI18n();
// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 请求头处理
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + Session.get('token'),
		'TENANT-ID': Session.getTenant(),
		'Content-Type':'multipart/form-data',
	};
});

// 请求参数处理
const formData = computed(() => {
	return Object.assign(props.data, { dir: props.dir });
});

// 上传前校检格式和大小
const handleBeforeUpload = (file: File) => {
	// 校检文件类型
	if (props.fileType.length) {
		const fileName = file.name.split('.');
		const fileExt = fileName[fileName.length - 1];
		const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
		if (!isTypeOk) {
			useMessage().error(`${t('excel.typeErrorText')} ${props.fileType.join('/')}!`);
			return false;
		}
	}
	// 校检文件大小
	if (props.fileSize) {
		const isLt = file.size / 1024 / 1024 < props.fileSize;
		if (!isLt) {
			useMessage().error(`${t('excel.sizeErrorText')} ${props.fileSize} MB!`);
			return false;
		}
	}
	number.value++;
	return true;
};
//当超出限制时，执行的钩子函数
const handleExceed=( files: File[], uploadFiles: UploadUserFile[])=>{
	useMessage().warning(`当前限制选择 ${props.limit}个文件，本次选择了${files.length}个文件，共选择了${files.length+uploadFiles.length}个文件`);
}
// 上传成功回调
function handleUploadSuccess(res: any, file: UploadFile, uploadFiles: UploadFiles) {
	if(!res){
		return;
	}
	if (res.code === 0) {
		uploadList.value.push({ name: file.name, url: res.data.url });
	} else {
		number.value--;
		useMessage().error(res.msg);
		fileUpload.value.handleRemove(file);
	}
	uploadedSuccessfully();
}

// 上传结束处理
const uploadedSuccessfully = () => {
	if (number.value > 0 && uploadList.value.length === number.value) {
		fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
		uploadList.value = [];
		number.value = 0;
		emit('change', listToString(fileList.value));
		emit('update:modelValue', listToString(fileList.value));
	}
};

const handleRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	fileList.value = fileList.value.filter((f) => !(f.name === uploadFile.name));
	emit('change', listToString(fileList.value));
	emit('update:modelValue', listToString(fileList.value));
};

const handlePreview = (file: any) => {
	other.downBlobFile(file.url, {}, file.name);
};
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const handleChange=(uploadFile: UploadFile, uploadFiles: UploadFiles)=>{
	fileList.value=uploadFiles;
}

/**
 * 将对象数组转为字符串，以逗号分隔。
 * @param list 待转换的对象数组。
 * @param separator 分隔符，默认为逗号。
 * @returns {string} 返回转换后的字符串。
 */
const listToString = (list: { url: string }[], separator = ','): string => {
	let strs = '';
	separator = separator || ',';
	for (let i in list) {
		if (list[i].url) {
			strs += list[i].url + separator;
		}
	}
	return strs !== '' ? strs.substr(0, strs.length - 1) : '';
};

const handleUploadError = () => {
	useMessage().error('上传文件失败');
};
//上传时参数
const handleProgress=(evt: UploadProgressEvent, uploadFile: UploadFile, uploadFiles: UploadFiles)=>{
	console.log(evt);
	console.log(uploadFile);
	console.log(uploadFiles);
}
//MD5验证
const calculateMD5=(file:File)=>{
	return new Promise<string>((resolve,reject)=>{
		if(!file){
			return reject(new Error("无效的文件对象"));
		}
		const reader=new FileReader();
		reader.onload=(e)=>{
			try {
				const wordArray=CryptoJS.lib.WordArray.create(e.target?.result);
				const md5=CryptoJS.MD5(wordArray).toString();
				resolve(md5);
			} catch (error:any) {
				reject(new Error("MD5计算失败："+error.message));
			}
		};
		reader.onerror=()=>reject(new Error("文件读取失败"));
		reader.readAsArrayBuffer(file);
	});
}
//覆盖默认上传
const handleHttpUpload=async (options:UploadRequestOptions)=>{
	const file=options.file;
	let formData = new FormData();
	const fileMD5=await calculateMD5(file);
	formData.append(props.file,file);
	formData.append('md5',fileMD5);
	formData.append('file', options.file);
	formData.append('dir', props.dir);
	try {
		const res=await request({
			url: props.uploadFileUrl,
			method: 'post',
			headers: {
				...headers.value,
				'Content-Type': 'multipart/form-data',
			},
			data: formData,
		})
		options.onSuccess(res);// 仅在成功时调用
		// 调用 el-form 内部的校验方法（可自动校验）
		formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
	} catch (error) {
		options.onError(error as any);
	}
}

/**
 * 监听 props 中的 modelValue 值变化，更新 fileList。
 */
watch(
	() => props.modelValue,
	(val) => {
		if (val) {
			let temp = 1;
			// 首先将值转为数组
			const list = Array.isArray(val) ? val : props?.modelValue?.split(',');
			// 然后将数组转为对象数组
			fileList.value = list.map((item) => {
				if (typeof item === 'string') {
					item = { name: item, url: item };
				}
				item.uid = item.uid || new Date().getTime() + temp++;
				return item;
			});
		} else {
			fileList.value = [];
			return [];
		}
	},
	{ deep: true, immediate: true }
);
//手动上传
const submitUpload = () => {
	if(fileList.value.length==0){
		useMessage().warning('请选择上传文件');
		return;
	}
	fileUpload.value!.submit();
	emit('change', listToString(fileList.value));
	emit('update:modelValue', listToString(fileList.value));
};
</script>
